var mongoose = require('mongoose');
var News = require('../models/news.model');
var Comment = require('../models/comment.model');
var async=require('async');

// 新增
exports.create = function(req,res,next){
    var news = new News(req.body);
    news.save()
    .then(data=>{
        res.json(data)
    })
    
}

//修改
exports.update = function(req,res,next){
  
    var id = req.params.id; // 获取ID
    News.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
    .then(data=>{
        res.json(data); // data返回的是你之前修改的那个数据内容
    })
}

//删除
exports.remove = function(req,res,next){
    var id = req.params.id;
    News.findByIdAndRemove(id,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })
} 


// exports.list = function(req,res,next){

//     console.log(req.body);
//     var page = (req.body.page) ? req.body.page : 1;
//     var rows = (req.body.rows) ? req.body.rows : 2;
//     console.log(rows,typeof rows);

//     var queryCondition = {};
//     var title;
//     if( req.body.title && req.body.title.trim().length>0 ){
//         title = req.body.title;
//         queryCondition = {"title":new RegExp(title,'i')}
//     }

//     if(req.body.cateId && req.body.cateId.trim().length>0){
//         cateId = req.body.cateId;
//         queryCondition = {
//             "cateId" : cateId
//         }
//     }

//     News.paginate(queryCondition, { page: page, limit: parseInt(rows) }, function(err, result) {
//         result.rows = result.docs;
//         delete result.docs;

//        res.json(result)
//     });
// }
exports.list = function(req,res,next){
    var page = (req.body.page) ? parseInt(req.body.page) : 1;
    var limit = (req.body.limit) ? parseInt(req.body.limit) : 10;
    var queryCondition = {};
    var cate;
    if( req.body.cate && req.body.cate.trim().length>0 ){
        cate = req.body.cate;
        queryCondition = {"cate":new RegExp(cate,'i')}
    }
    console.log(limit)
    News.paginate(queryCondition, { page: parseInt(page), limit: parseInt(limit) }, function(err, result) {
       //  result.limit = result.docs;
       //  delete result.docs;

       // res.json(result)
       async.map(result.docs,function(news,callback){
            Comment.count({newsID:news._id},function(err,count){
                news.commentCount=count;
                callback();
            })
       },function(err,results){
            result.limit=result.docs;
            delete result.docs;
            res.json(result);
       })
    });
}